package com.modules.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import com.modules.annotation.MenuMapping;
import com.modules.annotation.ResourceMapping;
import com.modules.annotation.ResourceMapping.Operation;
import com.wxp.entity.Resource;
import com.wxp.serviceImpl.ResourceServiceImpl;

public class StartupRunner implements CommandLineRunner{
	 private static final Logger logger = LoggerFactory.getLogger(StartupRunner.class);
	 
	 @Autowired
	 ApplicationContext applicationContext;
	 
	 @Autowired
	 private ResourceServiceImpl resourceService;
	 
	@Override
	public void run(String... arg0) throws Exception {
		logger.info("startup runner");
		AbstractHandlerMethodMapping<RequestMappingInfo> objHandlerMethodMapping = (AbstractHandlerMethodMapping<RequestMappingInfo>)applicationContext.getBean("requestMappingHandlerMapping");
	    Map<RequestMappingInfo, HandlerMethod> mapRet = objHandlerMethodMapping.getHandlerMethods();
	    //为了避免多次查询数据库，直接将现在数据库中所有的数据加载到list中
	    //List<String> resourceList = convertMap(resourceService.findAll());
	    //将逐渐转为Map
	    for(Map.Entry<RequestMappingInfo, HandlerMethod> entry : mapRet.entrySet()) {
	    		MenuMapping menuMapp = entry.getValue().getBeanType().getAnnotation(MenuMapping.class);
	    		RequestMapping sourceMapp = entry.getValue().getBeanType().getAnnotation(RequestMapping.class);
	    		if(menuMapp != null) {
				 	 //if(!resourceList.contains(menuMapp.operator())) {
    					 resourceService.save(new Resource(menuMapp.operator(),menuMapp.name(),null,sourceMapp==null?"":sourceMapp.name(),menuMapp.name(),Operation.MENU.toString(),menuMapp.parentOperator()));
    					 //resourceList.add(menuMapp.operator());
				 	 //}
	    			 if(entry.getValue().getMethodAnnotation(ResourceMapping.class)!=null&&entry.getValue().getMethodAnnotation(RequiresPermissions.class)!=null&&entry.getValue().getMethodAnnotation(RequestMapping.class)!=null) {
	    				  ResourceMapping resourceMapping = entry.getValue().getMethodAnnotation(ResourceMapping.class);
	    				  RequiresPermissions requiresPermiss = entry.getValue().getMethodAnnotation(RequiresPermissions.class);
	    				  String url = entry.getKey().getPatternsCondition().getPatterns().toArray()[0].toString();
	    				  //if(!resourceList.contains(url)) {
	    					  resourceService.save(new Resource(url,menuMapp.name(),convertString(requiresPermiss.value()),url,resourceMapping.name(),resourceMapping.operation().toString(),menuMapp.operator()));
	    					 // resourceList.add(url);
	    				  //}
	    				  //System.out.println("有对应注解"+"请求URL："+entry.getKey().getPatternsCondition().getPatterns().toArray()[0] +"   请求资源名称："+resourceMapping.name()+"   请求资源类型"+resourceMapping.operation()+"    菜单名称："+menuMapp.name()+"  "+"   权限："+convertString(requiresPermiss.value()));
	   	    	  	}
	    		}
	    }
	    logger.info("end runner");
		
	}
	private String convertString( String [] value) {
		String name = "";
		for(String val:value) {
			name = name+val+",";
		}
		if(StringUtils.isNotBlank(name)) {
			name= name.substring(0, name.lastIndexOf(","));
		}
		return name;
	}
	
	private List<String> convertMap(List<Resource> resourceList){
		List<String> list = new ArrayList<String>();
		for(Resource resource : resourceList) {
			if(!list.contains(resource.getOperator())) {
				list.add(resource.getOperator());
			}
		}
		return list;
	}
}
